//
//  BottomCommentViewController.m
//  DebugDemo
//
//  Created by XFB on 2019/1/11.
//  Copyright © 2019年 ZhouCheng. All rights reserved.
//  XIB的不怎么严谨，因为发送成功后清除输入框的内容高度不会回复原来的位置

#import "BottomCommentViewController.h"
#import "CustomInputView.h"

@interface BottomCommentViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstant;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstantH;
@property (weak, nonatomic) IBOutlet CustomInputView *inputView;

@end

@implementation BottomCommentViewController

/// 发送按钮点击
- (IBAction)sendButtonDidClick:(UIButton *)sender
{
    self.inputView.text = @"";
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupBasicSet];
    [self setupUI];
}

- (void)setupBasicSet
{
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.navigationItem.title = @"XIB约束设置输入框";
    /// 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)setupUI
{
    // 设置文本框占位文字
    _inputView.placeholder = @"我也来说几句";
    _inputView.placeholderColor = UIColorFromRGB(0xCCCCCC);
    _inputView.backgroundColor = UIColorFromRGB(0xEFEFEF);
    
    // 监听文本框文字高度改变
    __weak typeof(self) weakSelf = self;
    _inputView.TextHeightChangeBlock = ^(NSString *text, CGFloat textHeight){
        // 文本框文字高度改变会自动执行这个【block】，可以在这【修改底部View的高度】
        // 设置底部条的高度 = 文字高度 + textView距离上下间距约束
        // 为什么添加10 ？（10 = 底部View距离上（5）底部View距离下（5）间距总和）
        weakSelf.bottomConstantH.constant = textHeight + 10;
    };
    
    // 设置文本框最大行数
    _inputView.maxNumberOfLines = 4;
}

// 键盘弹出会调用
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 获取键盘frame
    CGRect endFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 获取键盘弹出时长
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    // 修改底部视图距离底部的间距
    _bottomConstant.constant = endFrame.origin.y != ScreenH?endFrame.size.height-BottomHeight:0;
    // 约束动画
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
